typedef void EventCallback(arg);

class EventBusTest {
  //单例模式
  EventBusTest._internal();

  static EventBusTest _singleton = new EventBusTest._internal();

  factory EventBusTest() => _singleton;

  var _emap = new Map<Object, List<EventCallback>>();

  /// 添加订阅者
  void on(eventName, EventCallback f) {
    if (eventName == null || f == null) return;
    _emap[eventName] ??= new List<EventCallback>();
    if (_emap.containsValue(f)) {
      return;
    }
    _emap[eventName].add(f);
  }

  ///移除订阅者
  void remove(eventName, [EventCallback f]) {
    var _list = _emap[eventName];
    if (eventName == null || _list == null) return;
    if (f == null) {
      _emap[eventName] = null;
    } else {
      _list.remove(f);
    }
  }

  void emit(eventName, [args]) {
    var list = _emap[eventName];
    if (eventName == null || list == null) return;
    var index = list.length - 1;

    for (int i = index; i >=0; i--) {
      var f = list[i];
      f(args);
    }
  }
}
